import React, { useState } from 'react';
import { Divider, Input, Button, Table, Space, Modal, message, Popover, Radio } from 'antd';
import { useNavigate } from 'react-router-dom';
import RoleModal from './Modal/RoleModal';
import axiosInstance from "../../component/axiosInstance.jsx";

const UserView = () => {
  const initialData = [];
  const navigate = useNavigate();
  const [data, setData] = useState(initialData);
  const [searchText, setSearchText] = useState('');
  const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
  const [isRoleModalVisible, setIsRoleModalVisible] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [currentUserId, setCurrentUserId] = useState(null);
  const [initialRoles, setInitialRoles] = useState([]);
  const [statusPopoverVisible, setStatusPopoverVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);

  const statusColors = {
    1: '#2ecc71', // 正常
    2: '#f39c12',  // 警告
    3: '#3498db',  // 冻结
    4: '#e74c3c',   // 禁用
    default: '#666', // 默认颜色（灰色）
  };

  const getStatusText = (status) => {
    switch (status) {
      case 1: return '正常';
      case 2: return '警告';
      case 3: return '冻结';
      case 4: return '禁用';
      default:
        console.warn(`未知状态值: ${status}`); // 记录日志以帮助调试
        return `未知状态： ${status}`; // 显示状态值以供调试
    }
  };

  const columns = [
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '状态',
      dataIndex: 'userStatus',
      key: 'userStatus',
      render: (text) => (
          <span style={{ color: statusColors[text] || 'inherit' }}>
          {getStatusText(text)}
        </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
          <Space size="middle">
            <Popover
                content={(
                    <div>
                      <Radio.Group
                          onChange={(e) => handleStatusChange(record, e.target.value)}
                          value={record.userStatus}
                      >
                        <Radio value={1} style={{ color: '#2ecc71' }}>正常</Radio>
                        <Radio value={2} style={{ color: '#f39c12' }}>警告</Radio>
                        <Radio value={3} style={{ color: '#3498db' }}>冻结</Radio>
                        <Radio value={4} style={{ color: '#e74c3c' }}>禁用</Radio>
                      </Radio.Group>
                    </div>
                )}
                title="选择状态"
                trigger="click"
                placement="top"  // 这里可以根据需要调整位置
            >
              <a >修改状态</a>
            </Popover>
            <a onClick={() => handlePermissionChange(record)}>修改角色</a>
          </Space>
      ),
    },
  ];

  const handleSearch = () => {
    const trimmedSearchText = searchText.trim();

    if (trimmedSearchText === '') {
      message.warning('请输入要搜索的用户名');
      return;
    }

    fetch(`http://localhost:8080/api/users/search?username=${encodeURIComponent(trimmedSearchText)}`)
        .then(response => response.json())
        .then(result => {
          // 检查响应状态码和消息
          if (result.code !== 200) {
            throw new Error(result.message || 'Network response was not ok');
          }

          const user = result.data; // 获取 data 中的用户对象

          if (user) {
            // 将单个用户对象转换为数组形式
            const userData = [user];
            console.log('Fetched Users:', userData); // 调试输出
            setData(userData);
          } else {
            message.info('没有找到该用户');
            setData([]); // 清空数据
          }
        })
        .catch(error => {
          console.error('获取用户信息失败：', error);
          message.error('获取用户信息失败，请稍后再试！');
        });
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys, selectedRows) => {
      setSelectedRowKeys(newSelectedRowKeys);
      console.log(`selectedRowKeys: ${newSelectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record) => ({
      disabled: record.userStatus !== 1,
    }),
  };

  // 获取用户列表
  const fetchUsers = async () => {
    console.log('获取用户列表中...');
    try {
      const response = await fetch(`http://localhost:8080/api/users`);
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      const result = await response.json();

      // 检查响应状态码和消息
      if (result.code !== 200) {
        throw new Error(result.message || '获取用户信息失败');
      }

      const users = result.data;

      // 确保后端返回的数据是数组形式，并按照 userId 升序排序
      const usersWithKeys = users
          .map(user => ({
            ...user,
            key: user.userId, // 使用 userId 作为 key，确保它是唯一的
          }))
          .sort((a, b) => a.userId - b.userId); // 按照 userId 升序排序

      console.log('获取到的用户信息:', usersWithKeys); // 调试输出

      setData(usersWithKeys);
    } catch (error) {
      console.error('获取用户信息失败：', error);
      message.error('获取用户信息失败，请稍后再试！');
    }
  };

  // 新增用户
  const handleAdd = () => {
    navigate('/admin/user/add'); // 跳转到新增用户页面
  };

  const handleDelete = () => {
    if (selectedRowKeys.length > 0) {
      setIsDeleteModalVisible(true);
    } else {
      message.error('请先选择要删除的用户');
    }
  };

  const handleOk = async () => {
    try {
      await deleteUser(selectedRowKeys);
      fetchUsers(); // 刷新用户列表
    } catch (error) {
      message.error('用户删除失败');
    } finally {
      setIsDeleteModalVisible(false);
    }
  };

  const handleCancel = () => {
    setIsDeleteModalVisible(false);
  };

  const deleteUser = async (userIds) => {
    try {
      console.log('删除用户中...');
      const response = await fetch('http://localhost:8080/api/users/delete', {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ userIds })
      });

      const result = await response.json();

      // 检查自定义响应状态码和消息
      if (result.code !== 200) {
        throw new Error(result.message || '删除失败');
      }

      message.success('用户删除成功');
    } catch (error) {
      console.error('删除用户信息失败：', error);
      message.error('删除用户信息失败，请稍后再试！');
    }
  };


  // 修改用户状态
  const handleStatusChange = (record, newStatus) => {
    setCurrentRecord(record);
    setStatusPopoverVisible(false);

    if (newStatus === record.userStatus) {
      return; // 如果新状态与当前状态相同，则不进行任何操作
    }

    // 发送请求更新用户状态
    updateStatus(record, newStatus);
  };

  // 发送请求更新用户状态
  const updateStatus = async (record, newStatus) => {
    try {
      const response = await fetch(`http://localhost:8080/api/users/${record.userId}/status?status=${newStatus}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
      });
      const result = await response.json();
      if (response.ok && result.code === 200) {
        // 更新本地数据
        const updatedData = data.map(item =>
            item.userId === record.userId ? { ...item, userStatus: newStatus } : item
        );
        setData(updatedData);
        message.success('用户状态更新成功');
      } else {
        console.error('更新用户状态失败：', data);
        message.error(data.message || '更新用户状态失败');
      }
    } catch (error) {
      console.error('更新用户状态失败：', error);
      message.error('更新用户状态失败，请稍后再试');
    }
  };

// 获取用户角色
  const handlePermissionChange = (record) => {
    axiosInstance.get(`http://localhost:8080/api/roles/${record.userId}/get-roles`)
        .then(response => {
          const data = response.data; // 解析JSON响应体
          console.log('获取到的角色信息:', data);

          if (response.status === 200 && data.code === 200) {
            const roles = data.data || [];
            console.log('用户角色:', roles);
            const roleIds = roles.map(role => role.roleId);
            setInitialRoles(roleIds);
            setCurrentUserId(record.userId);
            setIsRoleModalVisible(true);
          } else {
            throw new Error(data.message || `HTTP error! status: ${response.status}`);
          }
        })
        .catch(error => {
          console.error('获取用户角色失败：', error);
          message.error(error.response?.data?.message || '获取用户角色失败，请稍后再试！');
        });
  };

  // 处理角色更新
  const handleUpdateRoles = async (roleIds) => {
    try {
      const response = await axiosInstance.put(`/api/roles/${currentUserId}/update-roles`, { roles: roleIds }, {
        headers: {
          'Content-Type': 'application/json',
        }
      });

      const data = response.data;
      if (response.status === 200 && data.code === 200) {
        await message.success(data.message);
        fetchUsers(); // 刷新用户数据
      } else {
        await message.error(data.message || '角色更新失败，请稍后再试！');
      }
    } catch (error) {
      console.error('角色更新失败：', error);
      await message.error(error.response?.data?.message || '角色更新失败，请稍后再试！');
    }
  };

  // 修改用户
  const handleEdit = () => {
    console.log('编辑用户');
    // 在这里实现具体的编辑逻辑
  };

  const showModal = () => {
    setIsDeleteModalVisible(true);
  };

  const selectedUsers = data.filter(item => selectedRowKeys.includes(item.key));

  return (
      <div>
        <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
          <Input
              placeholder="输入用户名"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ width: 200, marginRight: 16 }}
          />
          <Button type="default" onClick={handleSearch} style={{ marginLeft: 8, width: 100 ,backgroundColor: '#1ab394',color: '#fff'}}>搜索</Button>
        </div>

        <Divider />
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'flex-start' }}>
          <Button type="default" onClick={fetchUsers} style={{ marginLeft: 8, width: 100 ,backgroundColor:"#23c6c8",color: '#fff'}}>查询</Button>
          <Button type="default" onClick={handleAdd} style={{ marginLeft: 8, width: 100 ,backgroundColor:"#1c84c6",color: '#fff'}}>新增</Button>
          <Button type="default" onClick={handleDelete} style={{ marginLeft: 8, width: 100 ,backgroundColor: '#ed5565',color: '#fff'}}>删除</Button>
        </div>
        <Divider />
        <Table
            rowSelection={rowSelection}
            columns={columns}
            dataSource={data}
        />
        {/* 角色模态窗口 */}
        <RoleModal
            visible={isRoleModalVisible}
            onClose={() => setIsRoleModalVisible(false)}
            onOk={handleUpdateRoles}
            userId={currentUserId}
            initialRoles={initialRoles}
        />
        {/* 删除确认模态窗口 */}
        <Modal
            title="确认删除"
            visible={isDeleteModalVisible}
            footer={[
              <div key="footer" style={{ display: 'flex', justifyContent: 'center' }}>
                <Button key="cancel" onClick={handleCancel} style={{ marginRight: 8 }}>
                  取消
                </Button>
                <Button key="submit" type="primary" onClick={handleOk} danger>
                  确认删除
                </Button>
              </div>
            ]}
            style={{ top: 200 }}
        >
          <p>您确定要删除以下用户吗？</p>
          <ul style={{ listStyleType: 'disc', paddingLeft: 20, marginBottom: 16 }}>
            {selectedUsers.map((user, index) => (
                <li key={index}>
                  {user.userName || `User ID: ${user.userId}`}
                </li>
            ))}
          </ul>
          <p style={{ color: 'red' }}>注意：此操作不可逆，请谨慎操作。</p>
        </Modal>
      </div>
  );
};

export default UserView;